package com.aididi.service;

import com.aididi.entity.IUsers;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import javax.annotation.PostConstruct;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Auther: zx.xu
 * @Description:
 */
@Service
public class IUserService {
    private final Map<Integer, IUsers> data = new ConcurrentHashMap<>();


    @PostConstruct
    private void init() {
        data.put(1, new IUsers(1, "张三", "z3@qq.com"));
        data.put(2, new IUsers(2, "李四", "l4@qq.com"));
        data.put(3, new IUsers(3, "王五", "w5@qq.com"));
    }

    public Flux<IUsers> list(){
        return Flux.fromIterable(this.data.values());
    }

    public Flux<IUsers> getByIds(Flux<Integer> ids) {
        return ids.flatMap(id -> Mono.justOrEmpty(this.data.get(id)));
    }

    public Mono<IUsers> getById(Integer id) {
        return Mono.justOrEmpty(this.data.get(id))
                .switchIfEmpty(Mono.error(new RuntimeException("资源未找到")));
    }

    public Flux<IUsers> createOrUpdate(Flux<IUsers> users) {
        return users.doOnNext(user -> this.data.put(user.getId(), user));
    }

    public Mono<IUsers> createOrUpdate(IUsers user) {
        this.data.put(user.getId(), user);
        return Mono.just(user);
    }

    public Mono<IUsers> delete(Integer id) {
        return Mono.justOrEmpty(this.data.remove(id));
    }


}
